﻿using Bot.Application.Dto;
using Bot.Domain;
using Bot.Domain.Entities;
using Bot.Domain.Enum;
using Bot.Domain.Interfaces;
using Comm100.Framework.Domain.Repository;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Bot.Application
{   
    public interface IQuickReplyItemVerifyDataManager
    {
        ErrorInfo VerifyId(Guid id);
        ErrorInfo VerifyCreate(QuickReplyItemCreateDto dto);
        ErrorInfo VerifyUpdate(QuickReplyItemUpdateDto dto);        
    }
    public class QuickReplyItemVerifyDataManager : IQuickReplyItemVerifyDataManager
    {
        private readonly IIntentDomainService _intentDomainService;
        private readonly IQuickReplyItemDomainService _quickReplyItemDomainService;
        public QuickReplyItemVerifyDataManager(
            IIntentDomainService intentDomainService,
            IQuickReplyItemDomainService quickReplyItemDomainService)
        {
            _intentDomainService = intentDomainService;
            _quickReplyItemDomainService = quickReplyItemDomainService;
        }
        public ErrorInfo VerifyCreate(QuickReplyItemCreateDto dto)
        {
            return VerifyDTO(dto.Type, dto.Order, dto.IntentId);
        }
        private ErrorInfo VerifyDTO(string type, int order, Guid? intentId)
        {
            ErrorInfo errorInfo = new ErrorInfo { Code = 1 };

            if (!Enum.TryParse(typeof(EnumQuickReplyType), type, true, out var t))
            {
                return APIHelper.GetErrorMessageByCode(54207);
            }
            if (order < 0)
            {
                return APIHelper.GetErrorMessageByCode(50004);
            }
            if (type.Equals("triggerAnIntent", StringComparison.OrdinalIgnoreCase))
            {
                if (!intentId.HasValue || intentId.Value == Guid.Empty)
                {
                    return APIHelper.GetErrorMessageByCode(50004);
                }
                var intent = _intentDomainService.Get(intentId.Value);
                if (intent == null || intent.IsDeleted)
                {
                    return APIHelper.GetErrorMessageByCode(51313, new object[] { intentId.Value });
                }
            }                          
            return errorInfo;
        }

        public ErrorInfo VerifyId(Guid id)
        {
            ErrorInfo errorInfo = new ErrorInfo { Code = 1 };

            var quickReplyItem = _quickReplyItemDomainService.Get(id);
            if (quickReplyItem == null || quickReplyItem.IsDeleted)
            {
                errorInfo = APIHelper.GetErrorMessageByCode(54210, new object[] { id });
            }

            return errorInfo;
        }

        public ErrorInfo VerifyUpdate(QuickReplyItemUpdateDto dto)
        {
            return VerifyDTO(dto.Type, dto.Order, dto.IntentId);
        }

    }
}
